package com.useeinfo.oa.modules.task.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.*;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.NumberUtil;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.NodeTypeEnum;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.task.entity.TaskOrder;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.task.dao.TaskOrderDao;
import com.useeinfo.oa.modules.task.entity.*;
import com.useeinfo.oa.modules.task.enums.TaskAssignTypeEnum;
import com.useeinfo.oa.modules.task.enums.TaskOrderLogOperationEnum;
import com.useeinfo.oa.modules.task.enums.TaskOrderStatusEnum;
import com.useeinfo.oa.modules.task.enums.TaskSourceEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @auther: bin.liu
 * @Date: 2019/6/25 9:30
 * @Description: 任务工单service
 */
@Service("taskOrderBiz")
public class TaskOrderBiz extends CrudBiz<TaskOrderDao, TaskOrder> {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private ResourceBiz resourceBiz;

    @Autowired
    private AreaBiz areaBiz;

    @Autowired
    private SystemUserBiz systemUserBiz;

    @Autowired
    private DictInfoBiz dictInfoBiz;

    @Autowired
    private AuditFlowBiz auditFlowBiz;

    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private PositionBiz positionBiz;

    @Autowired
    private SystemUserOrganizationBiz systemUserOrganizationBiz;

    @Autowired
    private TaskOrderLogBiz taskOrderLogBiz;

    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;

    @Autowired
    private PlanMessageSendBiz planMessageSendBiz;

    @Autowired
    private TaskOrderPartnerBiz taskOrderPartnerBiz;

    @Autowired
    private TaskFocusBiz taskFocusBiz;

    @Autowired
    private TaskAuditOrderBiz taskAuditOrderBiz;

    public List<Object> getOrganizationReceiveNum(String organizationId, String start, String end) {
        return dao.getOrganizationReceiveNum(organizationId, start, end);
    }

    public JSONArray getTags(TaskOrder taskOrder, SystemUser systemUser, String status) {
        return dao.getTags(taskOrder, systemUser, status);
    }


    /**
     * pc端新增工单
     * @param taskOrder 任务工单
     * @param createDate 创建时间
     * @param selectAreaId
     * @param selectUserId
     * @param recording
     * @param taskOrderStatus
     * @param selectTaskTypeId
     * @param selectCompleteAuditFlowId 选择的审批流
     * @param sImg1
     * @param sImg2
     * @param sImg3
     * @param sImg4
     * @param sImg5
     * @param pic1
     * @param pic2
     * @param pic3
     * @param pic4
     * @param pic5
     * @param systemUser
     * @param requireFinishTime
     * @return ResultDto
     */
    public ResultDto addTaskOrderPC(TaskOrder taskOrder,
                                    String createDate,
                                    String selectAreaId,
                                    String selectUserId,
                                    String recording,
                                    String taskOrderStatus,
                                    String selectTaskTypeId,
                                    String selectCompleteAuditFlowId,
                                    String sImg1,
                                    String sImg2,
                                    String sImg3,
                                    String sImg4,
                                    String sImg5,
                                    MultipartFile pic1,
                                    MultipartFile pic2,
                                    MultipartFile pic3,
                                    MultipartFile pic4,
                                    MultipartFile pic5,
                                    SystemUser systemUser,
                                    String requireFinishTime){
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if(enterprise == null){
            return ResultUtil.error("session已过期");
        }
        if (StringUtils.isBlank(selectUserId)) {
            return ResultUtil.error("请选择发布人");
        }
        taskOrder.setEnterprise(enterprise);

        if (StringUtils.isNotBlank(createDate)) {
            taskOrder.setCreateDate(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", createDate));
        }

        if (StringUtils.isNotBlank(requireFinishTime)){
            taskOrder.setRequireFinishTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm", requireFinishTime));
        }

        String savePath1 = FileUtils.fileUpload(pic1, ConstantKeyFilePath.TASK_IMG_DIR, ConstantKeyFilePath.TASK_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        String savePath2 = FileUtils.fileUpload(pic2, ConstantKeyFilePath.TASK_IMG_DIR, ConstantKeyFilePath.TASK_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        String savePath3 = FileUtils.fileUpload(pic3, ConstantKeyFilePath.TASK_IMG_DIR, ConstantKeyFilePath.TASK_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        String savePath4 = FileUtils.fileUpload(pic4, ConstantKeyFilePath.TASK_IMG_DIR, ConstantKeyFilePath.TASK_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        String savePath5 = FileUtils.fileUpload(pic5, ConstantKeyFilePath.TASK_IMG_DIR, ConstantKeyFilePath.TASK_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));

        TaskOrderLogOperationEnum operationEnum;
        String msg;
        if (taskOrder.getId() != null){
            // 编辑修改
            operationEnum = TaskOrderLogOperationEnum.UPDATE_ORDER;
            msg= " 已更新，请尽快接单";
            if (CollectionUtils.isNotEmpty(taskOrder.getTaskPhoto())){
                List<Resource> taskPhotos = new ArrayList<>(taskOrder.getTaskPhoto());
                taskPhotos.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
                if ("1".equals(sImg1)) {
                    if (StringUtils.isNotBlank(savePath1)) {
                        Resource resource1 = new Resource();
                        resource1.setPath(savePath1);
                        resource1.setResourceName("任务单图片");
                        resource1.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resource1.setEnterprise(enterprise);
                        resourceBiz.addOrUpdate(resource1);
                        taskPhotos.set(0, resource1);
                    } else {
                        taskPhotos.remove(0);
                    }
                }

                if ("1".equals(sImg2)) {
                    if (StringUtils.isNotBlank(savePath2)) {
                        Resource resource2 = new Resource();
                        resource2.setPath(savePath2);
                        resource2.setResourceName("任务单图片");
                        resource2.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resource2.setEnterprise(enterprise);
                        resourceBiz.addOrUpdate(resource2);
                        if (taskPhotos.size() == 1) {
                            taskPhotos.add(resource2);
                        } else {
                            taskPhotos.set(1, resource2);
                        }
                    } else {
                        taskPhotos.remove(1);
                    }
                }

                if ("1".equals(sImg3)) {
                    if (StringUtils.isNotBlank(savePath3)) {
                        Resource resource3 = new Resource();
                        resource3.setPath(savePath3);
                        resource3.setResourceName("任务单图片");
                        resource3.setEnterprise(enterprise);
                        resource3.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resourceBiz.addOrUpdate(resource3);
                        if (taskPhotos.size() == 2) {
                            taskPhotos.add(resource3);
                        } else {
                            taskPhotos.set(2, resource3);
                        }
                    } else {
                        taskPhotos.remove(2);
                    }
                }

                if ("1".equals(sImg4)) {
                    if (StringUtils.isNotBlank(savePath4)) {
                        Resource resource4 = new Resource();
                        resource4.setPath(savePath4);
                        resource4.setResourceName("任务单图片");
                        resource4.setEnterprise(enterprise);
                        resource4.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resourceBiz.addOrUpdate(resource4);
                        if (taskPhotos.size() == 3) {
                            taskPhotos.add(resource4);
                        } else {
                            taskPhotos.set(3, resource4);
                        }
                    } else {
                        taskPhotos.remove(3);
                    }
                }

                if ("1".equals(sImg5) && StringUtils.isNotBlank(savePath5)) {
                    if (StringUtils.isNotBlank(savePath5)) {
                        Resource resource5 = new Resource();
                        resource5.setPath(savePath5);
                        resource5.setEnterprise(enterprise);
                        resource5.setResourceName("任务单图片");
                        resource5.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resourceBiz.addOrUpdate(resource5);
                        if (taskPhotos.size() == 4) {
                            taskPhotos.add(resource5);
                        } else {
                            taskPhotos.set(4, resource5);
                        }
                    } else {
                        taskPhotos.remove(4);
                    }
                }
                taskOrder.setTaskPhoto(new HashSet<>(taskPhotos));
            }
            taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.valueOf(taskOrderStatus));

        } else {
            // pc端新增工单
            operationEnum = TaskOrderLogOperationEnum.CREATE_ORDER;
            msg= " 已发布，请尽快接单";
            taskOrder.setSerial(getCode(StringConverters.null2String(enterprise.getId())));
            taskOrder.setAssign(false);
            //状态设置为待接单
            taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.WAIT_TAKING);
            Set<Resource> resourceSet = new HashSet<>();
            if (StringUtils.isNotEmpty(savePath1)) {
                Resource resource1 = new Resource();
                resource1.setPath(savePath1);
                resource1.setResourceName("任务单图片");
                resource1.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource1);
                resourceSet.add(resource1);
            }

            if (StringUtils.isNotEmpty(savePath2)) {
                Resource resource2 = new Resource();
                resource2.setPath(savePath2);
                resource2.setResourceName("任务单图片");
                resource2.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource2);
                resourceSet.add(resource2);
            }

            if (StringUtils.isNotEmpty(savePath3)) {
                Resource resource3 = new Resource();
                resource3.setPath(savePath3);
                resource3.setResourceName("任务单图片");
                resource3.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource3);
                resourceSet.add(resource3);
            }

            if (StringUtils.isNotEmpty(savePath4)) {
                Resource resource4 = new Resource();
                resource4.setPath(savePath4);
                resource4.setResourceName("任务单图片");
                resource4.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource4);
                resourceSet.add(resource4);
            }

            if (StringUtils.isNotEmpty(savePath5)) {
                Resource resource5 = new Resource();
                resource5.setPath(savePath5);
                resource5.setResourceName("任务单图片");
                resource5.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource5);
                resourceSet.add(resource5);
            }
            taskOrder.setTaskPhoto(resourceSet);
        }

        taskOrder.setTaskSourceEnum(TaskSourceEnum.INNER_RELEASE);
        taskOrder.setTaskArea(areaBiz.findModel(StringConverters.null2Long(selectAreaId)));
        //发布人
        SystemUser selectUser = systemUserBiz.findModel(StringConverters.null2Long(selectUserId));//报修人
        taskOrder.setCreateUser(selectUser);
        taskOrder.setOrderType(dictInfoBiz.findModel(StringConverters.null2Long(selectTaskTypeId)));

        //设置审批流，没有则查看是否有默认审批流
        AuditFlow auditFlow1 = auditFlowBiz.findModel(StringConverters.null2Long(selectCompleteAuditFlowId));
        if (auditFlow1 != null){
            String newFlow = auditFlowBiz.updateFlowBySelf(enterprise.getId(), selectUser.getId(), auditFlow1.getFlow());
            taskOrder.setAuditFlow(auditFlow1);
            taskOrder.setLevel(auditFlow1.getLevel());
            taskOrder.setFlow(newFlow);
            taskOrder.setFlowName(auditFlow1.getFlowName());
            JSONArray jsonArray = JSON.parseArray(newFlow);
            if (jsonArray.size() > 0) {
                taskOrder.setAuditOrganization(null);
                taskOrder.setAuditUser(null);
                taskOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                taskOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if (NodeTypeEnum.POSITION.getCode().equals(nodeTypeEnum)) {
                    taskOrder.setAuditPosition(positionBiz.findModel(relationId));
                } else if (NodeTypeEnum.USER.getCode().equals(nodeTypeEnum)) {
                    taskOrder.setAuditUser(systemUserBiz.findModel(relationId));
                } else if (NodeTypeEnum.SELF.getCode().equals(nodeTypeEnum)) {
                    taskOrder.setAuditUser(systemUser);
                }
            }
        } else {
            QueryParam auditFlowParam = new QueryParam();
            auditFlowParam.getSqlMap().put("isDefaultV", StringConverters.null2String(true));
            auditFlowParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
            auditFlowParam.getSqlMap().put("remark", "TASK");
            List<AuditFlow> auditFlows = auditFlowBiz.findList(auditFlowParam);
            if (CollectionUtils.isNotEmpty(auditFlows)) {
                AuditFlow auditFlow = auditFlows.get(0);
                String newFlow = auditFlowBiz.updateFlowBySelf(enterprise.getId(), selectUser.getId(), auditFlow.getFlow());
                taskOrder.setFlowName(auditFlow.getFlowName());
                taskOrder.setFlow(newFlow);
                taskOrder.setLevel(auditFlow.getLevel());
                JSONArray jsonArray = JSON.parseArray(newFlow);
                if (jsonArray.size() > 0) {
                    taskOrder.setAuditOrganization(null);
                    taskOrder.setAuditUser(null);
                    taskOrder.setAuditPosition(null);
                    JSONObject j = jsonArray.getJSONObject(0);
                    Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                    Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                    String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                    taskOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                    if ("POSITION".equals(nodeTypeEnum)) {
                        taskOrder.setAuditPosition(positionBiz.findModel(relationId));
                    } else if ("USER".equals(nodeTypeEnum)) {
                        taskOrder.setAuditUser(systemUserBiz.findModel(relationId));
                    }
                }
            }
        }
        // 保存更新
        addOrUpdate(taskOrder);

        //操作日志
        taskOrderLogBiz.addLog(taskOrder, selectUser, operationEnum, enterprise, null);
        //发送消息
        List<Long> ids = new ArrayList<>();
        List<SystemUser> systemUsers1 = dao.sendTaskUsers(taskOrder, enterprise, null);
        String taskAuthorityName = Configuration.getConfigurationByName("taskAuthorityName");
        for (SystemUser user : systemUsers1) {
            //有接单权限
            if (systemAuthorityBiz.hasAuthAuthority(taskAuthorityName, user.getId(), enterprise.getId())) {
                ids.add(user.getId());
            }
        }
        if (ids.size() > 0) {
            planMessageSendBiz.senMsg(taskOrder.getId(), "task", enterprise, ids, "任务单: " + taskOrder.getSerial() + msg);
        }

        return ResultUtil.success();
    }

    /**
     * 获取流水号
     * @param enterpriseId
     * @return
     */
    public String getCode(String enterpriseId) {
        return dao.getCode(enterpriseId);
    }

    public String dashBoardInfo(String enterpriseId, String status, String date) {
        return dao.dashBoardInfo(enterpriseId, status, date);
    }

    public JSONArray getbetween(String enterpriseId, String start, String end, int type, boolean completed) {
        return dao.getbetween(enterpriseId, start, end, type, completed);
    }

    /**
     * 任务单详情
     * @param taskOrderId
     * @return
     */
    public ResultDto taskOrderDetail(String taskOrderId) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isBlank(taskOrderId)) {
            return ResultUtil.error("参数错误");
        }
        TaskOrder taskOrder = findModel(StringConverters.null2Long(taskOrderId));
        JSONObject jsonObject = taskOrder.toJSONObject();

        JSONObject workingTime = nowWorkHours(taskOrderId);
//        if (
//                TaskOrderStatusEnum.UNFINISHED.equals(taskOrder.getTaskOrderStatus())||
//                TaskOrderStatusEnum.REJECTED.equals(taskOrder.getTaskOrderStatus())
//        ) {
//            jsonObject.put("totalWorkingHours", workingTime.get("totalHours"));//总工时
//            jsonObject.put("workingHour", workingTime.get("receiveHours"));//我的工时
//        }

        jsonObject.put("totalWorkingHours", taskOrder.getTotalWorkingHours());//总工时
        jsonObject.put("workingHour", taskOrder.getWorkingHours());//我的工时

        // 返功前的实际按
        jsonObject.put("beforeHours", taskOrder.getWorkingHours());//退回重修前的我的工时
        jsonObject.put("beforeTotalHours", taskOrder.getTotalWorkingHours());//退回重修前的总工时

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("taskOrderId", taskOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        List<TaskOrderPartner> taskOrderPartners = taskOrderPartnerBiz.findList(queryParam);
        taskOrderPartners.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
        JSONArray partnerArray = new JSONArray();
        if (CollectionUtils.isNotEmpty(taskOrderPartners)) {
            for (TaskOrderPartner taskOrderPartner : taskOrderPartners) {
                JSONObject partnerObject = new JSONObject();
                partnerObject.put("userName", taskOrderPartner.getPartner().getUserName());
                partnerObject.put("userId", taskOrderPartner.getPartner().getId());
                partnerObject.put("partnerId", taskOrderPartner.getId());
                partnerObject.put("workingHours", taskOrderPartner.getWorkingHours());
                partnerObject.put("deleteStatus", taskOrderPartner.isDeleteStatus());
                partnerArray.add(partnerObject);
            }
        }
        jsonObject.put("partner", partnerArray);

        JSONArray flowArray = JSONArray.parseArray(taskOrder.getFlow());
        int auditLevel = taskOrder.getAuditLevel();
        // 当前用户
        systemUser = systemUserBiz.findModel(systemUser.getId());
        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        boolean leader = false;
        //所属部门
        Organization organization = null;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            for (SystemUserOrganization x : systemUserOrganizationSet) {
                if (sessionEnterprise.getId().equals(x.getOrganization().getEnterprise().getId())) {
                    leader = x.isLeader();
                    organization = x.getOrganization();
                }
            }
        }

        String takingAuthority = "ROLE_ENTERPRISE_TASK_ORDER_TAKING"; // 接单权限
        String auditAuthority = "ROLE_ENTERPRISE_TASK_ORDER_AUDIT"; // 审核权限
        String assignAuthorityName = "ROLE_ENTERPRISE_TASK_ORDER_ASSIGN"; // 指派权限
        // 按钮显示
        JSONArray jsonArray = new JSONArray();
        // 待接单
        if (TaskOrderStatusEnum.WAIT_TAKING.equals(taskOrder.getTaskOrderStatus())){
            if (systemAuthorityBiz.hasAuthAuthority(assignAuthorityName, systemUser.getId(), sessionEnterprise.getId())) {
                jsonArray.add("assignButton");
            }

            if (systemAuthorityBiz.hasAuthAuthority(takingAuthority, systemUser.getId(), sessionEnterprise.getId())) {
                //指定接单人的，需要判断我发起的工单有没有指派
                Position position=systemUser.getPosition(sessionEnterprise,systemUser.getPositionSet());//获取当前企业下的职位
                if(taskOrder.isAssign()&&(taskOrder.getTaskAssignUsers().contains(systemUser)||taskOrder.getTaskAssignPositions().contains(position))){
                    jsonArray.add("takingButton");
                } else if (!taskOrder.isAssign()) {
                    // 如果不是指派的，但有接单权限，给按钮
                    jsonArray.add("takingButton");
                }
            }
        }
        // 待到场
        else if (TaskOrderStatusEnum.WAIT_PRESENCE.equals(taskOrder.getTaskOrderStatus())){
            if (taskOrder.getReceiveUser() != null && taskOrder.getReceiveUser() == systemUser) {
                jsonArray.add("presenceButton");
            }
        }
        // 待完成
        else if(TaskOrderStatusEnum.UNFINISHED.equals(taskOrder.getTaskOrderStatus())){
            if (taskOrder.getReceiveUser() != null && taskOrder.getReceiveUser() == systemUser) {
                jsonArray.add("submitButton");
                jsonArray.add("saveButton");
            }
        }
        // 审批中
        else if (TaskOrderStatusEnum.IN_AUDITING.equals(taskOrder.getTaskOrderStatus())){
            if (systemAuthorityBiz.hasAuthAuthority(auditAuthority, systemUser.getId(), sessionEnterprise.getId())) {
                if (organization != null) {
                    if (taskOrder.getAuditUser() != null || taskOrder.getAuditPosition() != null) {
                        if ((taskOrder.getAuditOrganization() == organization && taskOrder.getAuditUser() == systemUser)) {
                            jsonArray.add("passButton");
                            jsonArray.add("rejectButton");
                        } else if (taskOrder.getAuditOrganization() == organization && taskOrder.getAuditPosition() == systemUser.getPosition(sessionEnterprise, systemUser.getPositionSet())) {
                            jsonArray.add("passButton");
                            jsonArray.add("rejectButton");
                        }
                    }
                }

                if (flowArray.size() > 0 && auditLevel + 1 == flowArray.size()) {
                    jsonObject.put("final", true);
                } else {
                    jsonObject.put("final", false);
                }
            }
        }
        //退回重做
        else if(TaskOrderStatusEnum.REJECTED.equals(taskOrder.getTaskOrderStatus())){
            if (taskOrder.getReceiveUser() != null && taskOrder.getReceiveUser() == systemUser) {
                jsonArray.add("presenceButton");
            }
        }
        jsonObject.put("buttons", jsonArray);
        jsonObject.put("isFocus", isFocus(taskOrderId, systemUser, sessionEnterprise));
        jsonObject.put("auditLog", auditLog(taskOrderId, sessionEnterprise));

        return ResultUtil.success(jsonObject);
    }

    //实时工时
    public JSONObject nowWorkHours(String id) {
        JSONObject jsonObject = new JSONObject();
        long totalHours = 0;
        TaskOrder taskOrder = dao.findModel(StringConverters.null2Long(id));
        if (taskOrder == null) {
            jsonObject.put("totalHours", totalHours);
            jsonObject.put("receiveHours", totalHours);
            return jsonObject;
        }
        if (TaskOrderStatusEnum.UNFINISHED.equals(taskOrder.getTaskOrderStatus())) {
            totalHours = DateTimeUtils.getDistanceMinutes(taskOrder.getPresenceTime(), new Date());
        }
        jsonObject.put("totalHours", taskOrder.getTotalWorkingHours() + totalHours);
        jsonObject.put("receiveHours", taskOrder.getWorkingHours() + totalHours);
        return jsonObject;
    }

    /**
     * 我的关注
     * @param taskOrderId
     * @param systemUser
     * @param enterprise
     * @return
     */
    public Boolean isFocus(String taskOrderId, SystemUser systemUser, Enterprise enterprise) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
        queryParam.getSqlMap().put("taskOrderId", taskOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        List<TaskFocus> taskFocusList = taskFocusBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(taskFocusList)) {
            return false;
        }
        return true;
    }

    /**
     * 审批记录
     */
    public JSONArray auditLog(String taskOrderId, Enterprise enterprise) {
        JSONArray result = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("taskOrderId", taskOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        queryParam.getSqlMap().put("taskOrderLogOperation", "AUDIT,REJECT");
        queryParam.setSqlOrder(" order by id  ");
        List<TaskOrderLog> list = taskOrderLogBiz.findList(queryParam);
        for (TaskOrderLog taskOrderLog : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", StringConverters.null2String(taskOrderLog.getUserName()));
            if (TaskOrderLogOperationEnum.AUDIT.equals(taskOrderLog.getTaskOrderLogOperationEnum())) {
                jsonObject.put("operation", "审批通过");
                jsonObject.put("status", "AUDIT");
            } else if (TaskOrderLogOperationEnum.REJECT.equals(taskOrderLog.getTaskOrderLogOperationEnum())) {
                jsonObject.put("operation", "审批驳回");
                jsonObject.put("status", "REJECT");
                jsonObject.put("remark", StringConverters.null2String(taskOrderLog.getRemark()));
            }
            result.add(jsonObject);
        }
        return result;
    }

    /**
     * 任务单列表
     * @param pageIndex
     * @param pageSize
     * @param status 状态
     * @param searchParam 查询参数
     * @param systemUser 用户
     * @param enterprise 企业
     * @param date 时间
     * @return
     */
    public ResultDto getTaskOrders(String pageIndex, String pageSize, String status, String searchParam, SystemUser systemUser, Enterprise enterprise, String date) {
        systemUser = systemUserBiz.findModel(systemUser.getId());
        Position position = systemUser.getPosition(enterprise, systemUser.getPositionSet());
        Set<Long> areaIds = new HashSet<>();
        if (systemUser.getAreaSet() != null) {
            for (Area area : systemUser.getAreaSet()) {
                areaIds.add(area.getId());
            }
        }

        // 组织关系，判断是否是主管
        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        //所属部门
        Organization organization = null;
        boolean leader = false;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            for(SystemUserOrganization x:systemUserOrganizationSet){
                if(enterprise.getId().equals(x.getOrganization().getEnterprise().getId())){
                    leader = x.isLeader();
                    organization=x.getOrganization();
                }
            }
        }

        String enterpriseId = StringConverters.null2String(enterprise.getId());
        String userId = StringConverters.null2String(systemUser.getId());
        String positionId = null;
        if (position != null){
            positionId = StringConverters.null2String(position.getId());
        }

        JSONObject result = dao.getTaskOrders(pageIndex, pageSize, enterpriseId, userId, areaIds, positionId, status, leader, organization, searchParam, date);
        return ResultUtil.success(result);
    }

    /**
     * app创建任务单
     */
    public ResultDto addTaskOrder(String assignUserIds, String assignPositionIds,String orderName, String taskContent,
                                  String taskAddress, String reportLevelId, String photoIds, String recordingId, String areaId,
             String orderTypeId, SystemUser systemUser, Enterprise enterprise,String requireFinishTime) {
        JSONObject result = new JSONObject();
        List<Long> ids = new ArrayList<>();

        if (systemUser == null || enterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isBlank(orderName)) {
            return ResultUtil.error("请输入任务工单名称");
        }
        if (StringUtils.isBlank(taskContent)) {
            return ResultUtil.error("请输入任务内容");
        }

        TaskOrder taskOrder = new TaskOrder();
        taskOrder.setCreateDate(new Date());
        taskOrder.setAssign(false);
        if(StringUtils.isNotBlank(requireFinishTime)){
            taskOrder.setRequireFinishTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm", requireFinishTime));
        }
        if (StringUtils.isNotBlank(assignUserIds) && StringUtils.isNotBlank(assignPositionIds)) {
            return ResultUtil.error("指派只能选择一种类型");
        } else if (StringUtils.isNotBlank(assignUserIds)) {
            String[] userArray = assignUserIds.split(",");
            taskOrder.setTaskAssignTypeEnum(TaskAssignTypeEnum.USER);
            Set<SystemUser> systemUserSet = new HashSet<>();
            for (String x : userArray) {
                systemUserSet.add(systemUserBiz.findModel(StringConverters.null2Long(x)));
                ids.add(StringConverters.null2Long(x));
            }

            taskOrder.setTaskAssignUsers(systemUserSet);
            taskOrder.setAssign(true);
        } else if (StringUtils.isNotBlank(assignPositionIds)) {
            String[] positionArray = assignPositionIds.split(",");
            taskOrder.setTaskAssignTypeEnum(TaskAssignTypeEnum.POSITION);
            Set<Position> positionHashSet = new HashSet<>();
            for (String x : positionArray) {
                positionHashSet.add(positionBiz.findModel(StringConverters.null2Long(x)));
                ids = systemUserBiz.getUserIdsByPosition(x,null, enterprise.getId() + "");
            }
            taskOrder.setAssign(true);
            taskOrder.setTaskAssignPositions(positionHashSet);
        }
        taskOrder.setSerial(dao.getCode(enterprise.getId().toString()));

        if (StringUtils.isNotBlank(photoIds)) {
            Set<Resource> resourceSet = new HashSet<>();
            String[] photoIdsArray = photoIds.split(",");
            for (String photoId : photoIdsArray) {
                resourceSet.add(resourceBiz.findModel(StringConverters.null2Long(photoId)));
            }
            taskOrder.setTaskPhoto(resourceSet);
        }

        if (StringUtils.isNotBlank(recordingId)) {
            taskOrder.setResource(resourceBiz.findModel(StringConverters.null2Long(recordingId)));
        }

        QueryParam systemUserOrganizationParam = new QueryParam();
        systemUserOrganizationParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
        List<SystemUserOrganization> systemUserOrganizations = systemUserOrganizationBiz.findList(systemUserOrganizationParam);
        if (CollectionUtils.isNotEmpty(systemUserOrganizations)) {
            taskOrder.setOrganization(systemUserOrganizations.get(0).getOrganization());
        }

        taskOrder.setTaskSourceEnum(TaskSourceEnum.INNER_RELEASE);
        taskOrder.setEnterprise(enterprise);
        taskOrder.setCreateUser(systemUser);
        taskOrder.setOrderName(orderName);
        taskOrder.setTaskContent(taskContent);
        taskOrder.setTaskAddress(taskAddress);
        taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.WAIT_TAKING);

        //审批流快照
        QueryParam auditFlowParam = new QueryParam();
        auditFlowParam.getSqlMap().put("isDefaultV", StringConverters.null2String(true));
        auditFlowParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        auditFlowParam.getSqlMap().put("remark", "TASK");
        List<AuditFlow> auditFlows = auditFlowBiz.findList(auditFlowParam);
        if (CollectionUtils.isNotEmpty(auditFlows)) {
            AuditFlow auditFlow = auditFlows.get(0);
            String newFlow = auditFlowBiz.updateFlowBySelf(enterprise.getId(), systemUser.getId(), auditFlow.getFlow());
            taskOrder.setFlowName(auditFlow.getFlowName());
            taskOrder.setFlow(newFlow);
            taskOrder.setLevel(auditFlow.getLevel());
            JSONArray jsonArray = JSON.parseArray(newFlow);
            if (jsonArray.size() > 0) {
                taskOrder.setAuditOrganization(null);
                taskOrder.setAuditUser(null);
                taskOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                taskOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if ("POSITION".equals(nodeTypeEnum)) {
                    taskOrder.setAuditPosition(positionBiz.findModel(relationId));
                } else if ("USER".equals(nodeTypeEnum)) {
                    taskOrder.setAuditUser(systemUserBiz.findModel(relationId));
                }
            }
        }

        // 任务类型
        if(StringUtils.isNotBlank(orderTypeId)){
            taskOrder.setOrderType(dictInfoBiz.findModel(StringConverters.null2Long(orderTypeId)));
        }

        // 任务区域
        if (StringUtils.isNotBlank(areaId)) {
            Area area = areaBiz.findModel(StringConverters.null2Long(areaId));
            taskOrder.setTaskArea(area);
        }
        addOrUpdate(taskOrder);

        taskOrderLogBiz.addLog(taskOrder, systemUser, TaskOrderLogOperationEnum.CREATE_ORDER, enterprise, null);
        //消息推送
        List<Long> ides = new ArrayList<>();
        logger.info("ids长度为：{}", ids);
        List<SystemUser> systemUsers1 = dao.sendTaskUsers(taskOrder, enterprise, ids);
        // 有接单权限的人
        String taskAuthorityName = Configuration.getConfigurationByName("taskAuthorityName");
        for (SystemUser user : systemUsers1) {
            if (systemAuthorityBiz.hasAuthAuthority(taskAuthorityName, user.getId(), enterprise.getId())) {
                ides.add(user.getId());
            }
        }
        if (ides.size() > 0) {
            planMessageSendBiz.senMsg(taskOrder.getId(), "task", enterprise, ides, "任务单: " + taskOrder.getSerial() + " 已发布，请尽快接单");
        }else{
            logger.info("任务单没有找到匹配的人员");
        }
        result.put("code", taskOrder.getSerial());
        result.put("id", taskOrder.getId());

        return ResultUtil.success(result);
    }

    /**
     * 参与人列表
     * @param id
     * @return
     */
    public ResultDto partnerList(String id) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);

        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        TaskOrder taskOrder = dao.findModel(StringConverters.null2Long(id));
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("taskOrderId", id);
        List<TaskOrderPartner> taskOrderPartners = taskOrderPartnerBiz.findList(queryParam);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (taskOrder.getReceiveUser() != null) {
            jsonObject.put("reason", "");
            jsonObject.put("name", StringConverters.null2String(taskOrder.getReceiveUser().getUserName()));
            jsonObject.put("phone", StringConverters.null2String(taskOrder.getReceiveUser().getMobile()));
            jsonObject.put("userId", StringConverters.null2String(taskOrder.getReceiveUser().getId()));
            jsonObject.put("tag", "main");
            jsonArray.add(jsonObject);
        }

        for (TaskOrderPartner taskOrderPartner : taskOrderPartners) {
            jsonObject = new JSONObject();
            jsonObject.put("reason", StringConverters.null2String(taskOrderPartner.getReason()));
            jsonObject.put("userId", StringConverters.null2String(taskOrderPartner.getPartner().getId()));

            // 岗位信息
            jsonObject.put("position ", StringConverters.null2String(systemUser.getPosition(sessionEnterprise,taskOrderPartner.getPartner().getPositionSet())));

            jsonObject.put("name", StringConverters.null2String(taskOrderPartner.getPartner().getUserName()));
            jsonObject.put("userName", StringConverters.null2String(taskOrderPartner.getPartner().getUserName()));
            jsonObject.put("phone", StringConverters.null2String(taskOrderPartner.getPartner().getMobile()));
            jsonObject.put("tag", "partner");
            jsonArray.add(jsonObject);
        }

        result.put("list", jsonArray);
        return ResultUtil.success(result);
    }

    /**
     * 添加参与人
     * @param taskOrderId
     * @param partnerArray
     * @return
     */
    public ResultDto addPartner(String taskOrderId, String partnerArray) {
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isNotBlank(partnerArray)) {
            JSONArray array = JSONArray.parseArray(partnerArray);
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < array.size(); i++) {
                JSONObject j = array.getJSONObject(i);
                String userId = AliJsonObjectCover.ObjectString(j, "userId");

                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("partnerId", userId);
                queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                queryParam.getSqlMap().put("taskOrderId", taskOrderId);
                List<TaskOrderPartner> list = taskOrderPartnerBiz.findList(queryParam);
                TaskOrderPartner taskOrderPartner;
                if (CollectionUtils.isNotEmpty(list)) {
                    taskOrderPartner = list.get(0);
                } else {
                    taskOrderPartner = new TaskOrderPartner();
                }

                if (StringUtils.isNotBlank(taskOrderId)) {
                    TaskOrder taskOrder = findModel(StringConverters.null2Long(taskOrderId));
                    taskOrderPartner.setTaskOrder(taskOrder);
                }
                taskOrderPartner.setEnterprise(sessionEnterprise);
                String reason = AliJsonObjectCover.ObjectString(j, "reason");
                if (StringUtils.isNotBlank(reason)) {
                    taskOrderPartner.setReason(reason);
                }
                String teamworkCatId = AliJsonObjectCover.ObjectString(j, "teamworkCatId");
                if (StringUtils.isNotBlank(teamworkCatId)) {
                    QueryParam dictInfoParam = new QueryParam();
                    dictInfoParam.getSqlMap().put("dictInfoId", StringConverters.null2String(teamworkCatId));
                    dictInfoParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                    taskOrderPartner.setTeamworkCat(CollectionUtils.isEmpty(dictInfoBiz.findList(dictInfoParam)) ? null : dictInfoBiz.findList(dictInfoParam).get(0));
                }
                if (StringUtils.isNotBlank(userId)) {
                    taskOrderPartner.setPartner(systemUserBiz.findModel(StringConverters.null2Long(userId)));
                }
                taskOrderPartnerBiz.addOrUpdate(taskOrderPartner);
                jsonArray.add(taskOrderPartner.getId());
            }

            jsonObject.put("partnerIds", jsonArray);
        }
        return ResultUtil.success(jsonObject);
    }

    /**
     * 移除参与人
     * @param id
     * @return
     */
    public ResultDto removePartner(String id) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        taskOrderPartnerBiz.deleteLogic(taskOrderPartnerBiz.findModel(StringConverters.null2Long(id)));
        return ResultUtil.success();
    }

    public ResultDto getDictSelect(String typeCode) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        return ResultUtil.success(dictInfoBiz.getDictSelect(sessionEnterprise, typeCode));
    }

    /**
     * 接单
     * @param taskOrderId
     * @return
     */
    public ResultDto taking(String taskOrderId) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        TaskOrder taskOrder = findModel(StringConverters.null2Long(taskOrderId));
        if (taskOrder == null) {
            return ResultUtil.error("工单信息错误");
        }
        //修改任务单状态
        taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.WAIT_PRESENCE);
        taskOrder.setReceiveUser(systemUser);
        taskOrder.setReceiveTime(new Date());
        addOrUpdate(taskOrder);
        //操作日志
        taskOrderLogBiz.addLog(taskOrder, systemUser, TaskOrderLogOperationEnum.TAKING, sessionEnterprise, null);

        //推送消息给发布人
        SystemUser createUser = taskOrder.getCreateUser(); // 发布人
        String content = "任务单:" + taskOrder.getSerial() + ",已被" + systemUser.getUserName() + "接单。";
        List<Long> ids = new ArrayList<>();
        ids.add(createUser.getId());
        planMessageSendBiz.senMsg(taskOrder.getId(), "task", sessionEnterprise, ids, content);

        return ResultUtil.success();
    }

    /**
     * 到场
     * @param taskOrderId
     * @param longitude
     * @param latitude
     * @return
     */
    public ResultDto presence(String taskOrderId, String longitude, String latitude) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

//        if (StringUtils.isBlank(presencePhotos)) {
//            return ResultUtil.error("请先拍照");
//        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("id", taskOrderId);
        List<TaskOrder> taskOrders = findList(queryParam);
        if (CollectionUtils.isEmpty(taskOrders)) {
            return ResultUtil.error("请传入正确的参数");
        }

//        JSONArray photos = JSONArray.parseArray(presencePhotos);
//        Set<Resource> set = new HashSet<>();
//        for (Object object : photos) {
//            Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
//            resource.setEnterprise(sessionEnterprise);
//            resource.setResourceName("到场照片");
//            resourceBiz.addOrUpdate(resource);
//            set.add(resource);
//        }

        TaskOrder taskOrder = taskOrders.get(0);
        taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.UNFINISHED);
//        taskOrder.setPresencePhoto(set);
        taskOrder.setPresenceTime(new Date());
//        taskOrder.setMark(false);
        if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
            logger.info("接收到的经纬度为：{}", longitude + "," + latitude);
            try {
                BigDecimal latitudeParam = new BigDecimal(latitude);
                BigDecimal longitudeParam = new BigDecimal(longitude);
                taskOrder.setLatitude(latitudeParam);
                taskOrder.setLongitude(longitudeParam);
            } catch (Exception e) {
                logger.info("获取经纬度异常");
            }
        }
        addOrUpdate(taskOrder);

        //日志
        taskOrderLogBiz.addLog(taskOrder, systemUser, TaskOrderLogOperationEnum.PRESENCE, sessionEnterprise, null);

        return ResultUtil.success();
    }

    /**
     * 上传照片及录音文件
     * @param file
     * @param type
     * @return
     */
    public ResultDto upload(MultipartFile file, String type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (file == null || StringUtils.isBlank(type)) {
            return ResultUtil.error("参数错误");
        }
        Resource resource = new Resource();
        String savePath = "";
        if ("mp3".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.TASK_MP3_DIR, ConstantKeyFilePath.TASK_MP3_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("任务描述录音");
            resource.setResourceTypeEnum(ResourceTypeEnum.MP3);
        } else if ("img".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.TASK_IMG_DIR, ConstantKeyFilePath.TASK_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("任务照片");
            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
        }
        resource.setPath(savePath);
        resource.setEnterprise(sessionEnterprise);
        resource.setCreateDate(new Date());
        resourceBiz.addOrUpdate(resource);
        return ResultUtil.success(resource.toJSONObject());
    }

    /**
     * 区域列表
     */
    public ResultDto areaList(String pageIndex, String pageSize, String searchParam) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("magicLike", searchParam);
        List<Area> list = areaBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        for (Area area : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", StringConverters.null2Long(area.getId()));
            String ids = area.getParentIds();
            StringBuilder names = new StringBuilder();
            if (StringUtils.isNotBlank(ids)) {
                String[] split = ids.split(",");
                for (String id : split) {
                    String name = areaBiz.findModel(StringConverters.null2Long(id)).getAreaName();
                    names.append(name).append("/");
                }
                names.append(area.getAreaName());
                jsonObject.put("names", names);
            } else {
                jsonObject.put("names", area.getAreaName());
            }
            jsonArray.add(jsonObject);
        }
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }

    /**
     * 指派人员
     * @param pageIndex
     * @param pageSize
     * @param userName
     * @param userIds
     * @return
     */
    public ResultDto getUser(String pageIndex, String pageSize, String userName, String userIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String userHql = "select obj from SystemUser obj where obj.deleteStatus = false and obj.operationRole='common' and " +
                "exists( select er from obj.enterpriseSet er" +
                " where er.id=" + enterprise.getId() + ")";
        if(StringUtils.isNotBlank(userName)){
            userHql += " and obj.userName like '%" + userName + "%'";
        }

        if (StringUtils.isNotBlank(userIds)){
            String ids = "";
            for (Object object : JSONArray.parseArray(userIds)) {
                if ("".equals(ids)) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                userHql += "  and obj.id not in (" + StringConverters.null2String(ids) + ")";
            }
        }

        JSONArray jsonArray = new JSONArray();
        List<SystemUser> systemUsers = systemUserBiz.hqlExcute(userHql, queryParam);
        for (SystemUser systemUser : systemUsers) {
            jsonArray.add(systemUser.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }


    /**
     * 指派岗位
     * @param pageIndex
     * @param pageSize
     * @param positionIds
     * @return
     */
    public ResultDto getPosition(String pageIndex, String pageSize, String positionIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String posHql = "select obj from Position obj where obj.deleteStatus = false and obj.enterprise.id=" + enterprise.getId();
        if (!StringConverters.null2String(positionIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(positionIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                posHql += "  and obj.id not in (" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        List<Position> positions = positionBiz.hqlExcute(posHql, queryParam);
        for (Position position : positions) {
            jsonArray.add(position.toJSONObject());
        }

        return ResultUtil.success(jsonArray);
    }

    /**
     * 保存指派人
     * @param assignIds
     * @param taskOrderId
     * @return
     */
    public ResultDto saveAssignList(String assignIds, String taskOrderId) {
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == sessionUser || null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
//        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        String[] assignIdsArray = assignIds.split(",");
        TaskOrder taskOrder = dao.findModel(StringConverters.null2Long(taskOrderId));
        Set<SystemUser> systemUsers = new HashSet<>();
        for (String id : assignIdsArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
            }
        }
        taskOrder.setAssign(true);
        taskOrder.setTaskAssignTypeEnum(TaskAssignTypeEnum.USER);
        taskOrder.setTaskAssignUsers(systemUsers);
        dao.update(taskOrder);
        //操作日志
        taskOrderLogBiz.addLog(taskOrder, sessionUser, TaskOrderLogOperationEnum.ASSIGN_USER, enterprise, null);

        return ResultUtil.success();
    }

    /**
     * 保存指派岗位
     * @param assignIds
     * @param taskOrderId
     * @return
     */
    public ResultDto saveAssignPositionList(String assignIds, String taskOrderId) {
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == sessionUser || null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
//        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        String[] assignIdsArr = assignIds.split(",");
        TaskOrder taskOrder = dao.findModel(StringConverters.null2Long(taskOrderId));
        Set<Position> positions = new HashSet<>();
        for (String id : assignIdsArr) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
            }
        }
        taskOrder.setAssign(true);
        taskOrder.setTaskAssignTypeEnum(TaskAssignTypeEnum.POSITION);
        taskOrder.setTaskAssignPositions(positions);
        dao.update(taskOrder);
        //操作日志
        taskOrderLogBiz.addLog(taskOrder, sessionUser, TaskOrderLogOperationEnum.ASSIGN_POSITION, enterprise, null);
        return ResultUtil.success();
    }

    /**
     * 参与人详情
     * @param taskOrderId
     * @param userId
     * @return
     */
    public ResultDto partnerDetail(String taskOrderId, String userId) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("taskOrderId", taskOrderId);
        queryParam.getSqlMap().put("partnerId", userId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        List<TaskOrderPartner> taskPartners = taskOrderPartnerBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(taskPartners)) {
            result = taskPartners.get(0).toJSONObject();
        }
        return ResultUtil.success(result);
    }

    public ResultDto process(String taskOrderId) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("taskOrderId", taskOrderId);
        String progress = "('CREATE_ORDER','TAKING','PRESENCE','COMPLETE')";//工作流程:创建，接单，到场，完成
        queryParam.getSqlMap().put("progress", progress);
        queryParam.setSqlOrder("order by id");
        List<TaskOrderLog> taskOrderLogs1 = taskOrderLogBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        for (TaskOrderLog taskOrderLog : taskOrderLogs1) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(taskOrderLog.getCreateDate()), ""));
            jsonObject.put("operation", taskOrderLog.getTaskOrderLogOperationEnum().getName());
            jsonObject.put("userName", taskOrderLog.getUserName());
            jsonObject.put("id", taskOrderLog.getId());
            jsonArray.add(jsonObject);
        }
        TaskOrder taskOrder = dao.findModel(StringConverters.null2Long(taskOrderId));
        //审批记录
        Set<TaskAuditOrder> taskAuditOrders = taskOrder.getTaskAuditOrders();
        taskAuditOrders.forEach(x -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("operation", x.getPass() ? (NumberUtil.convert(x.getLevel()) + "级审核") : "驳回");
            jsonObject.put("userName", x.getAuditUser().getUserName());
            jsonObject.put("id", x.getId());
            jsonObject.put("createDate", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(x.getCreateDate()), ""));
            jsonArray.add(jsonObject);
        });
        //对jsonArray进行排序
        jsonArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getDate("createDate")));
        JSONObject result = new JSONObject();
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }


    /**
     * 关注/取消关注
     */
    public ResultDto focus(String taskOrderId, Boolean type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || enterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (type) {
            //关注
            TaskFocus taskFocus = new TaskFocus();
            taskFocus.setEnterprise(enterprise);
            taskFocus.setSystemUser(systemUser);
            taskFocus.setTaskOrder(dao.findModel(StringConverters.null2Long(taskOrderId)));
            taskFocusBiz.addOrUpdate(taskFocus);
        } else {
            //取消关注
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
            queryParam.getSqlMap().put("taskOrderId", taskOrderId);
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
            List<TaskFocus> taskFocusList = taskFocusBiz.findList(queryParam);
            for (TaskFocus taskFocus : taskFocusList) {
                taskFocusBiz.delete(taskFocus.getId());
            }
        }
        return ResultUtil.success();
    }

    /**
     * 审批
     */
    public ResultDto audit(String taskOrderId, Boolean type, String remark) {
        String content = "";
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        List<SystemUser> systemUsers = new ArrayList<>();
        TaskOrder taskOrder = dao.findModel(StringConverters.null2Long(taskOrderId));
        JSONArray jsonArray = JSONArray.parseArray(taskOrder.getFlow());
        List<Long> ids = new ArrayList<>();
        //审批通过，推送给接单人和下一级审批者
        if (type) {
            //任务单中的审批流快照
            int auditLevel = taskOrder.getAuditLevel();
            content = "任务单" + taskOrder.getSerial() +"," + systemUser.getUserName() + "审核通过。";
            if (jsonArray.size() > 0 && auditLevel + 1 < jsonArray.size()) {
                taskOrder.setAuditLevel(auditLevel + 1);
                taskOrder.setAuditUser(null);
                taskOrder.setAuditOrganization(null);
                taskOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(auditLevel + 1);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                taskOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if ("POSITION".equals(nodeTypeEnum)) {
                    taskOrder.setAuditPosition(positionBiz.findModel(relationId));
                    systemUsers = dao.confirmSendUser(sessionEnterprise, positionBiz.findModel(StringConverters.null2Long(relationId)), organizationBiz.findModel(organizationId), null);
                } else if ("USER".equals(nodeTypeEnum)) {
                    taskOrder.setAuditUser(systemUserBiz.findModel(relationId));
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organizationBiz.findModel(organizationId), systemUserBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("SELF".equals(nodeTypeEnum)) {
                    taskOrder.setAuditUser(taskOrder.getCreateUser());
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organizationBiz.findModel(organizationId), systemUser);
                }
                jsonObject.put("final", false);
                taskAuditOrderBiz.saveOrUpdate(taskOrder, systemUser, true, remark, null,auditLevel);
//                taskOrderLogBiz.addLog(taskOrder, systemUser, TaskOrderLogOperationEnum.AUDIT, sessionEnterprise, null);
            } else if (jsonArray.size() > 0 && auditLevel + 1 >= jsonArray.size()) {
                jsonObject.put("final", true);
                content = "任务单" + taskOrder.getSerial() + "已经审核通过。";
                taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.COMPLETED);
                // 审批人显示终审人员信息
                taskOrder.setAuditUser(systemUser);
                taskAuditOrderBiz.saveOrUpdate(taskOrder, systemUser, true, remark,null, auditLevel);
//                taskOrderLogBiz.addLog(taskOrder, systemUser, TaskOrderLogOperationEnum.AUDIT, sessionEnterprise, null);
//                taskOrderLogBiz.addLog(taskOrder, taskOrder.getReceiveUser(), TaskOrderLogOperationEnum.FINISH, sessionEnterprise, null);
            }
        }
        else {
            //驳回，推送给接单人
            int level = taskOrder.getAuditLevel() + 1;
            content = "任务单审核" + taskOrder.getSerial() +"," + systemUser.getUserName() + "审核退回，请及时处理。";
            //退回重修
            jsonObject.put("final", false);
            taskOrder.setTaskFinishTime(null);
            taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.REJECTED);
            if (StringUtils.isBlank(remark)) {
                return ResultUtil.error("请输入驳回理由");
            }

            if (jsonArray.size() > 0) {
                taskOrder.setAuditUser(null);
                taskOrder.setAuditOrganization(null);
                taskOrder.setAuditPosition(null);
                taskOrder.setAuditLevel(0);
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                taskOrder.setAuditOrganization(organizationBiz.findModel(StringConverters.null2Long(organizationId)));
                if ("POSITION".equals(nodeTypeEnum)) {
                    taskOrder.setAuditPosition(positionBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("USER".equals(nodeTypeEnum)) {
                    taskOrder.setAuditUser(systemUserBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("SELF".equals(nodeTypeEnum)) {
                }
            }
            taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.REJECTED);
            taskAuditOrderBiz.saveOrUpdate(taskOrder, systemUser, false,null, remark, level);
//            taskOrderLogBiz.addLog(taskOrder, systemUser, TaskOrderLogOperationEnum.REJECT, sessionEnterprise, remark);
        }

        addOrUpdate(taskOrder);
        for (SystemUser systemUser1 : systemUsers) {
            ids.add(systemUser1.getId());
        }
        if(!ids.contains(taskOrder.getReceiveUser().getId())){
            ids.add(taskOrder.getReceiveUser().getId());
        }
        //推送消息
        if (ids.size() > 0) {
            planMessageSendBiz.senMsg(taskOrder.getId(), "task", sessionEnterprise, ids, content);
        }

        return ResultUtil.success(jsonObject);
    }

    public ResultDto finalAudit(String taskOrderId, String remark, String score) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        TaskOrder taskOrder = findModel(StringConverters.null2Long(taskOrderId));
        taskOrder.setLastRemark(StringConverters.null2String(remark));
        taskOrder.setLastScore(StringConverters.null2Int(score));
        // 审批人显示终审人员信息
        taskOrder.setAuditUser(systemUser);
        addOrUpdate(taskOrder);
        return ResultUtil.success();
    }

    /**
     * 人员工时统计
     * @param startDateTime
     * @param endDateTime
     * @param organizationId
     * @return
     */

    public JSONArray getHoursChartsData(String startDateTime, String endDateTime, String organizationId,String enterpriseId) {
        JSONArray result = new JSONArray();
        List<Object> hoursChartsData = dao.getHoursChartsData(startDateTime, endDateTime, enterpriseId, organizationId);
        for (Object data : hoursChartsData) {
            result.add(StringConverters.null2Int(data));
        }
        return result;
    }

    /**
     * 维修工单(今日)
     *
     * @return
     */
    public JSONObject taskOrderCount(String enterpriseIds) {
        JSONObject result = new JSONObject();
        if (StringUtils.isBlank(enterpriseIds)) {
            result.put("todayCount", 0);
            result.put("finishCount", 0);
            result.put("taskingCount", 0);
            return result;
        }
        String todayStr = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(new Date()));
        //总工单数(今日创建的维修单数)
        QueryParam queryParam1 = new QueryParam();
        queryParam1.getSqlMap().put("enterpriseIds", enterpriseIds);
        queryParam1.getSqlMap().put("beforeCreateDate", todayStr);
        Long todayCount = this.totalRecord(queryParam1.getSqlMap());
        //维修完成(今日完成的维修单数)
        QueryParam queryParam2 = new QueryParam();
        queryParam2.getSqlMap().put("enterpriseIds", enterpriseIds);
        queryParam2.getSqlMap().put("taskOrderStatus", TaskOrderStatusEnum.COMPLETED.getCode());
        queryParam2.getSqlMap().put("beforeTaskFinishTime", todayStr);
        Long finishCount = this.totalRecord(queryParam2.getSqlMap());
        //维修中(已接单还未完成的维修单数)
        QueryParam queryParam3 = new QueryParam();
        queryParam3.getSqlMap().put("enterpriseIds", enterpriseIds);
        String orderStatus = TaskOrderStatusEnum.WAIT_PRESENCE.getCode()
                + "," + TaskOrderStatusEnum.UNFINISHED.getCode()
                + "," + TaskOrderStatusEnum.REJECTED.getCode()
                + "," + TaskOrderStatusEnum.IN_AUDITING.getCode();
        queryParam3.getSqlMap().put("taskOrderStatus", orderStatus);
        Long taskingCount = this.totalRecord(queryParam3.getSqlMap());

        result.put("todayCount", todayCount);
        result.put("finishCount", finishCount);
        result.put("taskingCount", taskingCount);
        return result;
    }


    /**
     * 完成工单
     * @param taskOrderId 任务单id
     * @param participantInputs 参与人工时列表
     * @param finishPhotos 工单图片
     * @param unFinishReason 为完成理由
     * @param finishDescription 完成结果描述
     * @return ResultDto
     */
    public ResultDto completeTask(String taskOrderId, String participantInputs, String finishPhotos, String unFinishReason, String finishDescription) {

        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        TaskOrder taskOrder = findModel(StringConverters.null2Long(taskOrderId));
        if (taskOrder == null) {
            return ResultUtil.error("任务不存在！");
        }

        if (StringUtils.isNotBlank(finishPhotos)) {
            JSONArray photos = JSONArray.parseArray(finishPhotos);
            Set<Resource> set = new HashSet<>();
            for (Object object : photos) {
                Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
                if (resource != null) {
                    resource.setEnterprise(sessionEnterprise);
                    resource.setResourceName("完成照片");
                    resourceBiz.addOrUpdate(resource);
                    set.add(resource);
                }
            }
            if (set != null) {
                taskOrder.setTaskFinishPhoto(set);
            }
        }

        // 总工时
        long totalWorkingHours = taskOrder.getTotalWorkingHours();
        //主要负责人工时
        long receiveUserWorkingHours = taskOrder.getWorkingHours();

        taskOrder.setUnFinishReason(StringConverters.null2String(unFinishReason));
        taskOrder.setFinishDescription(StringConverters.null2String(finishDescription));


        //工时计算
        //最新增加的工时
        long thisHours = DateTimeUtils.newGetDiffMinutesTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", DateTimeUtils.format(taskOrder.getPresenceTime(), "yyyy-MM-dd HH:mm:ss")), new Date());
        taskOrder.setWorkingHours(taskOrder.getWorkingHours() + thisHours);
//        taskOrder.setWorkingHours(receiveUserWorkingHours + thisHours);


        List<TaskOrderPartner> taskOrderPartners = new ArrayList<>();
        JSONArray participantInputsArray = JSON.parseArray(participantInputs);
        if (participantInputsArray.size() > 0) {
            for (int i = 0; i < participantInputsArray.size(); i++) {
                JSONObject j = participantInputsArray.getJSONObject(i);
                Long workingHours = AliJsonObjectCover.ObjectLong(j, "workingHours");
                if (workingHours == null) {
                    return ResultUtil.error("参与人工时不能为空！");
                }
                if (workingHours > thisHours){
                    taskOrder.setWorkingHours(taskOrder.getWorkingHours() - thisHours);
                    addOrUpdate(taskOrder);
                    return ResultUtil.error("参与人工时不可大于主要负责人工时");
                }

                totalWorkingHours += workingHours;
                Long partnerId = AliJsonObjectCover.ObjectLong(j, "userId");
                QueryParam q = new QueryParam();
                q.getSqlMap().put("partnerId", partnerId == null ? "-1" : partnerId + "");
                q.getSqlMap().put("taskOrderId", taskOrder.getId() + "");
                q.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                List<TaskOrderPartner> taskOrderPartnerList = taskOrderPartnerBiz.findList(q);
                if (CollectionUtils.isEmpty(taskOrderPartnerList)) {
                    return ResultUtil.error("参与人不存在！");
                }
                TaskOrderPartner taskOrderPartner = taskOrderPartnerList.get(0);
                taskOrderPartner.setWorkingHours(taskOrderPartner.getWorkingHours() + workingHours);
                taskOrderPartners.add(taskOrderPartner);
            }
        }
        if (participantInputsArray.size() > 0) {
            taskOrder.setTotalWorkingHours(totalWorkingHours +  thisHours );
        } else {
            // 没有参与人的情况下，  主负责时间 = 总时间
            taskOrder.setTotalWorkingHours(taskOrder.getWorkingHours());
        }

        taskOrder.setTaskFinishTime(new Date());
        if(taskOrder.getFlow() != null && taskOrder.getFlow() != ""){
            // 配置了审批流，到审批流程
            taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.IN_AUDITING);
        } else {
            // 没有配置审批流,直接到已结束列表
            taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.COMPLETED);
        }
        addOrUpdate(taskOrder);
        taskOrderPartners.forEach(taskOrderPartner -> taskOrderPartnerBiz.addOrUpdate(taskOrderPartner));
        taskOrderLogBiz.addLog(taskOrder, systemUser, TaskOrderLogOperationEnum.COMPLETE, sessionEnterprise, null);

        //消息推送
        String auditAuthority = "ROLE_ENTERPRISE_TASK_ORDER_AUDIT";
        String content = "";
        List<SystemUser> systemUsers = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        logger.info("审批流信息：{}", taskOrder.getFlow());
        if (taskOrder.getFlow() != null) {
            content = "任务工单: " + taskOrder.getSerial() + " 已完成,待审核";
            JSONArray jsonArray = JSONArray.parseArray(taskOrder.getFlow());
            if (jsonArray != null && jsonArray.size() > 0) {
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Organization organization = organizationBiz.findModel(StringConverters.null2Long(organizationId));
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                if ("POSITION".equals(nodeTypeEnum)) {
                    systemUsers = dao.confirmSendUser(sessionEnterprise, positionBiz.findModel(StringConverters.null2Long(relationId)), organization, null);
                } else if ("USER".equals(nodeTypeEnum)) {
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organization, systemUserBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("SELF".equals(nodeTypeEnum)) {
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organization, systemUser);
                }

                for (SystemUser systemUser1 : systemUsers) {
                    if (systemAuthorityBiz.hasAuthAuthority(auditAuthority, systemUser1.getId(), sessionEnterprise.getId())) {
                        ids.add(systemUser1.getId());
                    }
                }
            }
        } else {
            // 没有配置审批流,直接到已结束列表
            content = "任务工单: " + taskOrder.getSerial() + " 已完成";
            // 没有审批，把消息推送给发布人
            ids.add(taskOrder.getCreateUser().getId());
        }

        if (ids.size() > 0) {
            planMessageSendBiz.senMsg(taskOrder.getId(), "task", sessionEnterprise, ids, content);
        }

        return ResultUtil.success();
    }
}
